﻿using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;

namespace SLControlLibrary
{
    public class PopupDragDrop
    {
        Popup popup;
        FrameworkElement popupChild;
        double mouseX, mouseY;
        bool mouseCaptured;

        private PopupDragDrop() { }

        /// <summary>
        /// Allow a Popup window to be dragged. Also sets the Popup's Child property.
        /// </summary>
        public static void Attach(Popup popup, FrameworkElement popupChild)
        {
            PopupDragDrop pdd = new PopupDragDrop { popup = popup, popupChild = popupChild };
            popup.Child = popupChild;
            popupChild.MouseLeftButtonDown += pdd.MouseLeftButtonDown;
            popupChild.MouseLeftButtonUp += pdd.MouseLeftButtonUp;
            popupChild.MouseMove += pdd.MouseMove;
        }

        void MouseMove(object sender, MouseEventArgs e)
        {
            if (mouseCaptured)
            {
                double deltaY = e.GetPosition(null).Y - mouseY;
                double deltaX = e.GetPosition(null).X - mouseX;
                popup.VerticalOffset += deltaY;
                popup.HorizontalOffset += deltaX;

                // constrain the popup to the bounds of the silverlight window
                if (popup.VerticalOffset < 0) popup.VerticalOffset = 0;
                if (popup.HorizontalOffset < 0) popup.HorizontalOffset = 0;
                double maxY = Application.Current.Host.Content.ActualHeight - popupChild.ActualHeight;
                if (popup.VerticalOffset > maxY) popup.VerticalOffset = maxY;
                double maxX = Application.Current.Host.Content.ActualWidth - popupChild.ActualWidth;
                if (popup.HorizontalOffset > maxX) popup.HorizontalOffset = maxX;

                mouseY = e.GetPosition(null).Y;
                mouseX = e.GetPosition(null).X;
            }
        }

        void MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            popupChild.ReleaseMouseCapture();
            mouseCaptured = false;            
            mouseY = 0;
            mouseX = 0;
        }

        void MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            popupChild.CaptureMouse();
            mouseCaptured = true;
            mouseY = e.GetPosition(null).Y;
            mouseX = e.GetPosition(null).X;
        }
    }
}
